package com.yuexiao.config;

import com.alibaba.fastjson.JSON;
import com.yuexiao.entity.ResultInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录失败时调用
 */
@Component
@Slf4j
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException exception) throws IOException, ServletException {

        Map<String, Object> responseData = new HashMap<>();
        String msg = "未知错误";
//        if (exception instanceof UsernameNotFoundException) {//此异常不会抛出，会被捕捉然后抛出为BadCredentialsException
//            responseData.put("status", 7001);
//            responseData.put("msg", "用户不存在!");
//        }
        if (exception.getMessage().contains("Bad credentials")) {
            msg = "验证码错误";
        } else {
            msg = exception.getMessage();
        }
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setStatus(200);
        httpServletResponse.getWriter().write(JSON.toJSONString(ResultInfo.error(msg)));
    }
}